package com.zyh.server.controller;

import com.zyh.server.entity.Goods;
import com.zyh.server.service.GoodsService;
import com.zyh.server.utils.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @Author: zyh
 * @Date: 2024-11-14-11:49
 * @Description
 */
@Tag(name = "商品模块")
@Slf4j
@RestController //@Controller + @ResponseBody后端传递json数据
@RequestMapping("/goods")
@CrossOrigin(origins = "*") //允许跨域请求
public class GoodsController {
	@Autowired
	private GoodsService goodsService;

	@Operation(summary = "商品列表(分页)")
	@Parameters({
			@Parameter(name = "current", description = "当前页码", in = ParameterIn.QUERY),
			@Parameter(name = "size", description = "每页显示记录数", in = ParameterIn.QUERY)
	})
	@GetMapping("/list")
	public R getAllGoods(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
	                     @RequestParam(value = "pageSize", defaultValue = "3") Integer pageSize) {
		log.info("请求商品列表页码:{},每页显示记录数:{}", pageNum, pageSize);
		return goodsService.findAllGoods(pageNum, pageSize);
	}

	@Operation(summary = "添加商品")
	@Parameters({@Parameter(name = "goods", description = "json格式的商品信息")})
	@PostMapping("/save")
	public R save(@RequestBody Goods goods) {
		boolean flag = goodsService.save(goods);
		return flag ? R.ok().setMsg("商品添加成功！") : R.fail().setMsg("商品添加失败！");
	}

	@Operation(summary = "查询单条商品")
	@Parameters({@Parameter(name = "id", description = "商品id")})
	@GetMapping("/{id}")
	public R getOneGoodsById(@PathVariable("id") Integer id) {
		Goods goodsById = goodsService.getById(id);
		return Objects.isNull(goodsById) ? R.fail().setMsg("商品不存在!") : R.ok().setData(goodsById);
	}


	@Operation(summary = "修改商品")
	@Parameters({@Parameter(name = "goods", description = "json格式的商品信息")})
	@PutMapping("/update")
	public R update(@RequestBody Goods goods) {
		boolean flag = goodsService.updateById(goods);
		return flag ? R.ok().setMsg("商品修改成功！") : R.fail().setMsg("商品修改失败！");
	}
}
